// cloudfunctions/getMyWants/index.js
const cloud = require('wx-server-sdk');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    const { userId, page = 1, pageSize = 10 } = event;
    
    // 验证参数
    if (!userId) {
      return { success: false, message: '缺少userId参数' };
    }
    
    // 计算分页参数
    const skip = (page - 1) * pageSize;
    
    // 查询我想要的产品记录
    const wantsResult = await db.collection('user_wants')
      .where({
        userId: userId,
        status: 'active' // 只查询活跃状态的想要记录
      })
      .orderBy('createTime', 'desc')
      .skip(skip)
      .limit(pageSize)
      .get();
    
    // 提取所有productId
    const productIds = wantsResult.data.map(item => item.productId);
    
    // 查询总数量
    const totalResult = await db.collection('user_wants')
      .where({
        userId: userId,
        status: 'active'
      })
      .count();
    
    // 如果没有产品ID，直接返回空结果
    if (productIds.length === 0) {
      return {
        success: true,
        data: {
          list: [],
          total: totalResult.total
        },
        message: '获取我想要的产品成功'
      };
    }
    
    // 根据productIds批量查询产品信息
    const productsResult = await db.collection('blindbox_products')
      .where({
        productId: _.in(productIds)
      })
      .get();
    
    // 将产品信息合并到想要记录中
    const productsMap = {};
    productsResult.data.forEach(product => {
      productsMap[product.productId] = product;
    });
    
    const resultList = wantsResult.data.map(want => {
      const product = productsMap[want.productId] || {};
      return {
        ...want,
        productInfo: product
      };
    });
    
    return {
      success: true,
      data: {
        list: resultList,
        total: totalResult.total
      },
      message: '获取我想要的产品成功'
    };
  } catch (error) {
    console.error('获取我想要的产品失败', error);
    return {
      success: false,
      message: error.message || '服务器错误',
      error: error.message
    };
  }
};